package com.ygqh.baby.service.wechat.api;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.ContentType;
import com.foxinmy.weixin4j.http.HttpClient;
import com.foxinmy.weixin4j.http.HttpClientException;
import com.foxinmy.weixin4j.http.HttpMethod;
import com.foxinmy.weixin4j.http.HttpRequest;
import com.foxinmy.weixin4j.http.HttpResponse;
import com.foxinmy.weixin4j.http.entity.FormUrlEntity;
import com.foxinmy.weixin4j.http.entity.HttpEntity;
import com.foxinmy.weixin4j.http.entity.StringEntity;
import com.foxinmy.weixin4j.http.factory.HttpClientFactory;
import com.foxinmy.weixin4j.model.Consts;
import com.foxinmy.weixin4j.mp.api.MpApi;
import com.foxinmy.weixin4j.token.TokenHolder;
import com.foxinmy.weixin4j.util.URLEncodingUtil;
import com.ygqh.baby.service.wechat.model.Actions;
import com.ygqh.baby.service.wechat.model.UserActionReport.Aggregation;
import com.ygqh.baby.service.wechat.model.UserActionReport.TimeGranularity;
import com.ygqh.baby.service.wechat.model.UserActionSet;
import com.ygqh.baby.utils.DateConvertUtils;

/**
 * 上报网页转化行为数据
 * @author Ss
 *
 */
public class UserActionApi extends MpApi {

	private final TokenHolder tokenHolder;
	private final String user_action_sets_add_uri = "https://api.weixin.qq.com/marketing/user_action_sets/add?version=v1.0&access_token=%s";
	private final String user_action_sets_get_uri = "https://api.weixin.qq.com/marketing/user_action_sets/get?version=v1.0&access_token=%s";
	private final String user_action_uri = "https://api.weixin.qq.com/marketing/user_actions/add?version=v1.0&access_token=%s";
	private final String user_action_set_reports_uri = "https://api.weixin.qq.com/marketing/user_action_set_reports/get?version=v1.0&access_token=%s";

	private HttpClient httpClient;

	public UserActionApi(TokenHolder tokenHolder) {
		this.tokenHolder = tokenHolder;
		httpClient = HttpClientFactory.getInstance();
	}

	public JSONObject post(String url, Map<String, String> body) throws HttpClientException, WeixinException {
		url = String.format(url, tokenHolder.getAccessToken());
		System.out.println(url);
		HttpEntity entity = new FormUrlEntity(body);
		HttpRequest request = new HttpRequest(HttpMethod.POST, url);
		request.setEntity(entity);
		return doRequest(request);
	}

	public JSONObject post(String url, String body, ContentType contentType) throws HttpClientException, WeixinException {
		url = String.format(url, tokenHolder.getAccessToken());
		System.out.println(url);
		HttpEntity entity = new StringEntity(body, contentType);
		HttpRequest request = new HttpRequest(HttpMethod.POST, url);
		request.setEntity(entity);
		return doRequest(request);
	}

	public JSONObject get(String url, String body, ContentType contentType) throws HttpClientException, WeixinException {
		System.out.println(body);
		url = String.format(url, tokenHolder.getAccessToken());
		System.out.println(url);
		HttpEntity entity = new StringEntity("", contentType);
		HttpRequest request = new HttpRequest(HttpMethod.GET, url + body);
		request.setEntity(entity);
		return doRequest(request);
	}

	private JSONObject doRequest(HttpRequest request) throws HttpClientException, WeixinException {
		HttpResponse httpResponse = httpClient.execute(request);
		String response = new String(httpResponse.getContent());
		System.out.println(response);
		JSONObject jsonObject = JSONObject.parseObject(response);
		if (jsonObject.getInteger("errcode").compareTo(40001) == 0) {
			tokenHolder.refreshToken();
		}
		return jsonObject;
	}

	/**
	 * 
	 * @param userActionSet
	 * @return
	 * @throws WeixinException
	 * @throws HttpClientException
	 */
	public JSONObject addUserActionSets(UserActionSet userActionSet) throws WeixinException, HttpClientException {
		Map<String, String> body = new HashMap<>();
		body.put("type", userActionSet.getType().name());
		body.put("name", userActionSet.getName());
		body.put("description", userActionSet.getDescription());
		return post(user_action_sets_add_uri, body);
	}

	public JSONObject addUserActions(Actions actions) throws WeixinException, HttpClientException {
		return post(user_action_uri, JSON.toJSONString(actions), ContentType.APPLICATION_JSON);
	}

	public JSONObject getUserActionSets(String userActionSetId) throws HttpClientException, WeixinException {
		return get(user_action_sets_get_uri, "user_action_set_id=" + userActionSetId, ContentType.APPLICATION_JSON);
	}

	public JSONObject getUserActionSetReports(String userActionSetId, Date startDate, Date endDate, TimeGranularity timeGranularity, Aggregation aggregation) throws HttpClientException, WeixinException {
		StringBuffer sb = new StringBuffer();
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("start_date", DateConvertUtils.format(startDate));
		jsonObject.put("end_date", DateConvertUtils.format(endDate));
		sb.append("&user_action_set_id=").append(userActionSetId).append("&date_range=").append(URLEncodingUtil.encoding(
				jsonObject.toJSONString(), Consts.UTF_8, true))
			.append("&time_granularity=").append(timeGranularity.name()).append("&aggregation=").append(aggregation);
		return get(user_action_set_reports_uri, sb.toString(), ContentType.APPLICATION_JSON);
	}

}
